package com.ziq.zcamp.place

import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.*
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ScreenUtils
import com.facebook.drawee.view.SimpleDraweeView
import com.google.android.material.appbar.AppBarLayout
import com.scwang.smart.refresh.layout.api.RefreshHeader
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.*
import com.ziq.base.utils.SystemBarUtil
import com.ziq.base.view.drawable.gradientDrawableBuild
import com.ziq.base.view.webview.BaseWebViewActivity
import com.ziq.zcamp.R
import com.ziq.zcamp.api.respond.camp.CampConditionTree
import com.ziq.zcamp.api.service.ApiUrlHelper
import com.ziq.zcamp.bean.place.*
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.constant.PlaceSortType
import com.ziq.zcamp.databinding.FragmentPlaceListBinding
import com.ziq.zcamp.dialog.CampListFilterAreaDialog
import com.ziq.zcamp.dialog.CampUploadTypeSelectorDialog
import com.ziq.zcamp.life.CampLifeActivity
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.main.MainFragment
import com.ziq.zcamp.main.MainFragmentViewModel
import com.ziq.zcamp.manager.CampLifeManager
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.PrivacyManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.place.PlaceListFragmentViewModel.Companion.UI_MODEL_LIST
import com.ziq.zcamp.place.PlaceListFragmentViewModel.Companion.UI_MODEL_MAP
import com.ziq.zcamp.place.PlaceListFragmentViewModel.Companion.empty_id
import com.ziq.zcamp.search.SearchMainActivity
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.view.StatusView
import com.ziq.zcamp.view.layoutmanager.FilterAreaCategoryContentGridLayoutManager
import com.ziq.zcamp.view.layoutmanager.HorizontalPageLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import java.text.DecimalFormat

@AndroidEntryPoint
class PlaceListFragment : BaseFragment(R.layout.fragment_place_list), OnPlaceSelectResultListener, OnPlaceClickListener,
    AMap.OnInfoWindowClickListener, AMap.OnMarkerClickListener{

    private val mMainViewModel: MainFragmentViewModel by viewModels(ownerProducer = {
        parentFragment!!
    })

    private val binding : FragmentPlaceListBinding? by binding()
    private val mViewModel: PlaceListFragmentViewModel by viewModels()
    private val mPlaceAreaViewModel:CampListAreaViewModel by viewModels()

    var isAppBarClose = false
    var appBarOffset = 0

    //筛选
    var conditionCategoryAdapter : CampListConditionCategoryAdapter? = null //1级
    var conditionCategoryPanelAdapter : CampListConditionCategoryAdapter? = null //1级
    var filterConditionCategoryContentAdapter : FilterConditionCategoryContentAdapter? = null //2级
    var hotConditionAdapter : HotConditionAdapter? = null


    //列表模式下
    var adapter : CampListAdapter? = null
    //地图模式下
    var mapView: MapView? = null
    var aMap: AMap? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.root
        mViewModel.checkPermissionStatus()
        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mViewModel.locationGrantSharedFlow.collect{
                    binding?.flPermissionMask?.isVisible = !it
                    if(it){
                        initAfterGrantLocationPermission()
                    }
                }
            }
        })
    }

    private var hasInit = false
    private fun initAfterGrantLocationPermission(){
        if(!hasInit){
            hasInit = true
            initBaseModelUI()
            initBaseModelClick()

            updateModelUi()
        }
    }


    override fun onResume() {
        super.onResume()
        if(mMainViewModel.currentTabValue.value == MainFragment.MainTab.MAIN_TAB_PLACE.value){
            mViewModel.checkLocationPermissionForResume(requireActivity())
        }

        CampLifeManager.requestMyCampData()
        mPlaceAreaViewModel.requestAreaList()
        mPlaceAreaViewModel.requestConditionList()
        mPlaceAreaViewModel.requestHotCondition()

        uiResume()
    }

    private fun initBaseModelUI(){
        //去设置
        binding?.btnSetting?.click {
            AppUtils.launchAppDetailsSettings()
        }

        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mViewModel.progressShow.collect{
                    if(it) {
                        showLoading()
                    } else {
                        hideLoading()
                    }
                }
            }
        })

        //顶部搜索
        binding?.clTopSearchBarBg?.post {
            val lp = binding?.clTopSearchBarBg?.layoutParams as ConstraintLayout.LayoutParams?
            if((binding?.container?.height?:0) > 0){
                lp?.height = binding?.container?.height?:0
            } else {
                lp?.height = ScreenUtils.getScreenHeight()
            }
            binding?.clTopSearchBarBg?.layoutParams = lp
        }

        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mViewModel.updateForMyLatLng.collect{ amapLocation ->
                    if(amapLocation == null){
                        onPlaceSelectUpdate(mViewModel.selectedItem.value?:PlaceAreaViewModel.wholeCountry)
                    } else {
                        amapLocation.let {
                            if(mViewModel.myLatLng != null){
                                if(mPlaceAreaViewModel.filterAreaData.value?.provinces != null){
                                    val selectedArea = mPlaceAreaViewModel.findTargetArea(it.adCode)
                                    mViewModel.selectedItem.value = selectedArea?: PlaceAreaViewModel.wholeCountry
                                    onPlaceSelectUpdate(mViewModel.selectedItem.value!!)
                                } else {
                                    mPlaceAreaViewModel.requestAreaList(onSuccess = {respond->
                                        val selectedArea = mPlaceAreaViewModel.findTargetArea(it.adCode)
                                        mViewModel.selectedItem.value = selectedArea?: PlaceAreaViewModel.wholeCountry
                                        onPlaceSelectUpdate(mViewModel.selectedItem.value!!)
                                    }, onFail = {
                                        mViewModel.selectedItem.value = PlaceAreaViewModel.wholeCountry
                                        onPlaceSelectUpdate(mViewModel.selectedItem.value!!)
                                    })
                                }
                            }
                        }
                    }

                }
            }
        })

        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mViewModel.searchKeyword.collect{
                    if (it.keyword?.isNotEmpty() == true){
                        binding?.tvSearch?.text = it.keyword
                    }
                }
            }
        })

        //refresh 相关
        binding?.refreshLayoutTop?.let {
            SystemBarUtil.getStatusBarsHeight(it){ height ->
                val fltLp = it.layoutParams as ConstraintLayout.LayoutParams?
                fltLp?.topMargin = height
                it.layoutParams = fltLp
            }
        }

        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mViewModel.placeListRequestFinished.collect{
                    if(it) {
                        binding?.refreshLayoutTop?.finishRefresh()
                        binding?.refreshLayoutTop?.finishLoadMore()
                        binding?.topLoadingView?.stopAnim()
                        binding?.topLoadingView?.alpha = 0f
                        binding?.clTopSearchBar?.alpha = 1.0f

                        binding?.refreshLayout?.finishRefresh()
                        binding?.refreshLayout?.finishLoadMore()
                    }
                }
            }
        })


        binding?.refreshLayoutTop?.setEnableLoadMore(false)
        binding?.refreshLayoutTop?.setOnRefreshListener {
            binding?.refreshLayoutTop?.finishRefresh(0)
            binding?.clTopSearchBar?.alpha = 0.0f
            binding?.topLoadingView?.startAnim()
            mViewModel.onRefresh()
        }

        var needUpdateAlpha = false
        binding?.refreshLayoutTop?.setOnMultiListener(object : SimpleMultiListener() {
            override fun onHeaderMoving(
                header: RefreshHeader?,
                isDragging: Boolean,
                percent: Float,
                offset: Int,
                headerHeight: Int,
                maxDragHeight: Int
            ) {
                super.onHeaderMoving(header, isDragging, percent, offset, headerHeight, maxDragHeight)
                if(isDragging || needUpdateAlpha){
                    var alpha = percent
                    if(alpha > 1.0f){
                        alpha = 1.0f
                    } else if(alpha < 0f){
                        alpha = 0f
                    }
                    binding?.clTopSearchBar?.alpha = 1.0f - alpha
                    binding?.topLoadingView?.alpha = alpha
                }
            }
        })
        binding?.topCarRefreshHeader?.visibility = View.INVISIBLE
        binding?.topCarRefreshHeader?.setLoadingStateChangeListener { oldState, newState ->
            if(oldState == RefreshState.PullDownToRefresh && newState == RefreshState.ReleaseToRefresh){
                //刷新
                needUpdateAlpha = false
                binding?.refreshLayoutTop?.setReboundDuration(250)
            } else if(newState == RefreshState.PullDownToRefresh){
                //取消刷新
                needUpdateAlpha = true
                binding?.refreshLayoutTop?.setReboundDuration(500)
            } else if(newState == RefreshState.None){
                needUpdateAlpha = false
                binding?.refreshLayoutTop?.setReboundDuration(500)
            }
        }

        //菜单栏目
        val params: CoordinatorLayout.LayoutParams = binding?.appBarLayout?.getLayoutParams() as CoordinatorLayout.LayoutParams
        params.behavior = AppBarLayout.Behavior().apply {
            setDragCallback(object : AppBarLayout.Behavior.DragCallback() {
                override fun canDrag(appBarLayout: AppBarLayout): Boolean {
                    return mViewModel.uiModel == PlaceListFragmentViewModel.UI_MODEL_LIST
                }
            })
        }
        binding?.appBarLayout?.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            val remain = appBarLayout.totalScrollRange + verticalOffset
            if(mViewModel.uiModel == PlaceListFragmentViewModel.UI_MODEL_LIST){
                appBarOffset = verticalOffset
            }
            if(remain <= 0){
                if(!isAppBarClose){
                    binding?.appBarLayout?.post {
                        updateUIForAppBar()
                    }
                }
                isAppBarClose = true
            } else if(remain >= 40.dp){
                if(isAppBarClose){
                    binding?.appBarLayout?.post {
                        updateUIForAppBar()
                    }
                }
                isAppBarClose = false
            }
        })


        //功能模块
        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                CampLifeManager.myCampData.collect{
                    val number = it.camping_count?:0
                    if(number > 0){
                        binding?.btnCampLife?.setBackgroundResource(R.drawable.icon_camp_list_camp_life)
                        binding?.lineCampLife?.visibility = View.VISIBLE
                        binding?.tvCampLifeNumber?.visibility = View.VISIBLE
                        binding?.tvCampLifeNumber?.text = "$number"
                    } else {
                        binding?.btnCampLife?.setBackgroundResource(R.drawable.icon_camp_list_camp_life_go)
                        binding?.lineCampLife?.visibility = View.GONE
                        binding?.tvCampLifeNumber?.visibility = View.GONE
                        binding?.tvCampLifeNumber?.text = ""
                    }
                }
            }
        })
        //过滤模块
        initFilterModel()


    }
    private fun initFilterModel(){
        binding?.clTopSearchBar?.let {
            SystemBarUtil.getStatusBarsHeight(it){height ->
                val fltLp = it.layoutParams as ConstraintLayout.LayoutParams?
                fltLp?.height = 50.dp + height
                it.layoutParams = fltLp
            }
        }

        mViewModel.campRankList.observe(viewLifecycleOwner) {
            if (it?.isNotEmpty() == true) {
                if(mViewModel.uiModel == UI_MODEL_LIST){
                    if(binding?.flFilter?.visibility == View.VISIBLE){
                        needUpdateRank = true
                    } else {
                        needUpdateRank = false
                        updateUIForRank(it)
                    }
                } else {
                    needUpdateRank = true
                }
            } else {
                binding?.clCampRankInfo?.visibility = View.GONE
                needUpdateRank = false
            }
        }

        //1级分类 类目
        binding?.rvCondition?.layoutManager = HorizontalPageLayoutManager(1, 3)
        binding?.rvCondition?.isNestedScrollingEnabled = false
        conditionCategoryAdapter = CampListConditionCategoryAdapter()
        conditionCategoryAdapter?.onClickListener = { position, category ->
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    if(category.children?.isNotEmpty() == true){
                        conditionCategoryPanelAdapter?.filterPanelPosition = position
                        conditionCategoryPanelAdapter?.notifyDataSetChanged()
                        binding?.appBarLayout?.setExpanded(false)
                        binding?.appBarLayout?.post {
                            binding?.flFilter?.visibility = View.VISIBLE
                            filterConditionCategoryContentAdapter?.setData(category.children, position)
                            filterConditionCategoryContentAdapter?.updateSelectedCondition(mViewModel.selectedCondition.value)
                        }
                    }
                })
            }
        }
        binding?.rvCondition?.adapter = conditionCategoryAdapter

        //分类面板
        conditionCategoryPanelAdapter = CampListConditionCategoryAdapter()
        conditionCategoryPanelAdapter?.inFilterPanel = true
        binding?.rvConditionPanel?.layoutManager = HorizontalPageLayoutManager(1, 3)
        binding?.rvConditionPanel?.adapter = conditionCategoryPanelAdapter
        binding?.rvConditionPanel?.isNestedScrollingEnabled = false
        conditionCategoryPanelAdapter?.onClickListener = { position, it ->
            if(it.children?.isNotEmpty() == true){
                conditionCategoryPanelAdapter?.filterPanelPosition = position
                conditionCategoryPanelAdapter?.notifyDataSetChanged()
                binding?.appBarLayout?.setExpanded(false)
                binding?.appBarLayout?.post {
                    binding?.flFilter?.visibility = View.VISIBLE
                    filterConditionCategoryContentAdapter?.setData(it.children, position)
                    filterConditionCategoryContentAdapter?.updateSelectedCondition(mViewModel.selectedCondition.value)

                }
            }
        }

        filterConditionCategoryContentAdapter = FilterConditionCategoryContentAdapter(requireContext())
        binding?.rvConditionCategoryContent?.layoutManager = FilterAreaCategoryContentGridLayoutManager(requireContext(), 3, filterConditionCategoryContentAdapter, filterConditionCategoryContentAdapter)
        binding?.rvConditionCategoryContent?.adapter = filterConditionCategoryContentAdapter
        binding?.rvConditionCategoryContent?.isNestedScrollingEnabled = false
        filterConditionCategoryContentAdapter?.onSelectListener = fun (categoryId:Int?, categoryType:Int?, conditionId:Int?, conditionName:String?) {
            conditionChange = true
            mViewModel.addCondition(categoryId, categoryType, conditionId, conditionName)
        }
        filterConditionCategoryContentAdapter?.onUnSelectListener = fun (categoryId:Int?, categoryType:Int?, conditionId:Int?, conditionName:String?) {
            conditionChange = true
            mViewModel.removeCondition(categoryId, categoryType, conditionId, conditionName)
        }

        mPlaceAreaViewModel.filterConditionData.observe(viewLifecycleOwner) {
            updateConditionData(it)
        }
        mViewModel.selectedCondition.observe(viewLifecycleOwner, Observer {
            it?.let {
                onConditionSelectUpdate(it)
            }
        })


        //热门筛选条件
        hotConditionAdapter = HotConditionAdapter()
        binding?.rvHotCondition?.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        binding?.rvHotCondition?.adapter = hotConditionAdapter
        binding?.rvHotCondition?.isNestedScrollingEnabled = false

        hotConditionAdapter?.onSelectListener = fun (categoryId:Int?, categoryType:Int?, conditionId:Int?, conditionName:String?) {
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    mViewModel.addCondition(categoryId, categoryType, conditionId, conditionName)
                    mViewModel.onRefresh(showProgress = true)
                })
            }
        }
        hotConditionAdapter?.onUnSelectListener = fun (categoryId:Int?, categoryType:Int?, conditionId:Int?, conditionName:String?) {
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    mViewModel.removeCondition(categoryId, categoryType, conditionId, conditionName)
                    mViewModel.onRefresh(showProgress = true)
                })
            }
        }
        mPlaceAreaViewModel.hotConditionData.observe(viewLifecycleOwner) {
            updateHotConditionData(it)
        }

    }
    private fun initBaseModelClick(){
        //搜索
        binding?.llSearchInfo?.click {
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    SearchMainActivity.open(it, SearchMainActivity.SOURCE_FROM_PLACE)
                })
            }
        }
        binding?.btnChangeToMap?.click {
            GlobalContextManager.getCurrentActivity()?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    changeModel(PlaceListFragmentViewModel.UI_MODEL_MAP)
                })
            }
        }
        binding?.btnChangeToList?.click {
            GlobalContextManager.getCurrentActivity()?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    changeModel(PlaceListFragmentViewModel.UI_MODEL_LIST)
                })
            }
        }

        //功能模块
        binding?.btnCampLife?.click {
            GlobalContextManager.getCurrentActivity()?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    CampLifeActivity.open(GlobalContextManager.appContext!!)
                })
            }
        }
        binding?.btnMapModel?.click {
            GlobalContextManager.getCurrentActivity()?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    changeModel(PlaceListFragmentViewModel.UI_MODEL_MAP)
                })
            }
        }
        binding?.btnCampUpload?.click {
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    LoginActivity.checkLogin(object : ActionAfterLogin {
                        override fun action() {
                            activity?.let {
                                showCampUploadTypeSelector(it)
                            }
                        }
                    })
                })
            }
        }

        binding?.btnRankMore?.click {
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    PlaceRankActivity.open(it, mViewModel.selectedItem.value?.ad_code?:" ")
                })
            }
        }

        //过滤模块
        binding?.llAreaInfo?.click {
            activity?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    CampListFilterAreaDialog(it, mViewModel, mPlaceAreaViewModel, this).show()
                })
            }
        }
        binding?.btnFilterDistance?.click {
            onOrderSelect(PlaceSortType.Distance)
        }
        binding?.btnFilterPopularity?.click {
            onOrderSelect(PlaceSortType.Popularity)
        }
        binding?.btnFilterGood?.click {
            onOrderSelect(PlaceSortType.GoodEvaluation)
        }
        binding?.vFilterPanelBg?.click {
            hideConditionFilter()
        }
        binding?.btnConditionClean?.click {
            conditionChange = true
            if((conditionCategoryPanelAdapter?.filterPanelPosition?:-1) != -1){
                try {
                    conditionCategoryPanelAdapter?.dataList?.get(conditionCategoryPanelAdapter?.filterPanelPosition?:0)?.let {
                        if(it.children?.isNotEmpty() == true){
                            for(item in it.children!!){
                                mViewModel.removeCondition(item.id)
                            }
                        }
                    }
                }catch (e:Exception){}
            }
        }
        binding?.btnConditionCommit?.click {
            hideConditionFilter()
        }
    }
    fun uiResume(){
        if(mViewModel.uiModel == UI_MODEL_MAP){//map
            if(mapView == null){
                initMapModelUI()
            }
            mapView?.onResume()
            aMap?.isMyLocationEnabled = true
        }else {
            if(adapter == null){
                initListModelUI()
            }
        }
    }

    fun showLoading(){
        binding?.flProgress?.visibility = View.VISIBLE
        binding?.ldView?.startAnim()
    }

    fun hideLoading(){
        binding?.flProgress?.visibility = View.GONE
        binding?.ldView?.stopAnim()
    }



    fun onOrderSelect(type: PlaceSortType){
        activity?.let {
            PrivacyManager.checkPrivacy(it, action = {
                mViewModel.currentScreen = type
                updateUIForOrderFilter()
                mViewModel.onRefresh(showProgress = true)
                hideConditionFilter()
            })
        }
    }

    override fun onPlaceSelect(item : AreaItem, source:String) {
        onPlaceSelectUpdate(item)
        mPlaceAreaViewModel.updateHistoryCityByClick(item)
        hideConditionFilter()
    }

    var conditionChange = false
    fun hideConditionFilter(){
        binding?.flFilter?.visibility = View.GONE
        if(needUpdateRank){
            mViewModel.campRankList.getValue()?.let {
                updateUIForRank(it)
            }
        }
        if(conditionChange){
            conditionChange = false
            mViewModel.onRefresh(showProgress = true)
        }
    }

    //切换模式
    fun changeModel(model:String){
        mViewModel.uiModel = model
        uiResume()

        if(mViewModel.uiModel == UI_MODEL_MAP){
            binding?.appBarLayout?.setExpanded(false)
            binding?.clFilterInfo?.background = gradientDrawableBuild {
                solidColor = Color.parseColor("#ffffff")
                cornerRadii = floatArrayOf(
                    0f, 0f,
                    0f, 0f,
                    0f, 0f,
                    16.dp.toFloat(), 16.dp.toFloat()
                )
            }
        } else {
            mapView?.onPause()
            val totalScrollRange = (binding?.appBarLayout?.totalScrollRange?:0)
            if( totalScrollRange > 0 && totalScrollRange + appBarOffset != 0){
                binding?.appBarLayout?.setExpanded(true)
            }
            binding?.clFilterInfo?.background = null
        }

        updateModelUi()

        if(mViewModel.uiModel == UI_MODEL_MAP){
            updateMapModelUI(true)
        } else {
            if(needUpdateRank){
                mViewModel.campRankList.value?.let {
                    updateUIForRank(it)
                }
            }
        }


    }

    //选择上传的营地类型
    fun showCampUploadTypeSelector(activity: FragmentActivity, dismissListener :(()->Unit)? = null){
        val dialog = CampUploadTypeSelectorDialog.Builder(activity).setCallback(object : CampUploadTypeSelectorDialog.ActionCallBack {
            override fun onActionClick(
                dialog: CampUploadTypeSelectorDialog,
                position: Int
            ) {
                dialog.dialogDismiss()
                BaseWebViewActivity.openUrl(activity, ApiUrlHelper.instance.getUrl(H5Url.CAMP_UPLOAD.getUrlWithAtom()), false)
//                when(position){
//                    0->{
//                        CampUploadActivity.open(activity,false, 1)
//                    }
//                    1->{
//                        CampUploadActivity.open(activity,false, 2)
//                    }
//                    2->{
//                        CampUploadPageActivity.open(activity)
//                    }
//                }
            }

        }).build()
        dialog.setOnDismissListener {
            dismissListener?.invoke()
        }
        dialog.show()
    }

    var needUpdateRank = false
    fun updateUIForRank(campRankList : List<CampListItem>){
        binding?.ivRankImage1?.click {  }
        binding?.ivRankImage2?.click {  }
        binding?.ivRankImage3?.click {  }
        if(campRankList.isNotEmpty()){
            binding?.clCampRankInfo?.visibility = View.VISIBLE
        } else {
            binding?.clCampRankInfo?.visibility = View.GONE
        }
        when{
            campRankList.size == 1 ->{
                campRankList[0].let {
                    binding?.ivRankImage1?.isVisible = true
                    binding?.vRankMask1?.isVisible = true
                    binding?.ivRankLevel1?.isVisible = true
                    binding?.llRankInfo1?.isVisible = true
                    binding?.tvRankName1?.text = it.campName
                    binding?.tvRankDistance1?.text = it.distance?.toFloat()?.let{ distance ->
                        "${DecimalFormat("0.##").format(distance / 1000)}km"
                    }

                    binding?.vRankMask2?.isVisible = false
                    binding?.ivRankLevel2?.isVisible = false
                    binding?.llRankInfo2?.isVisible = false
                    binding?.vRankMask3?.isVisible = false
                    binding?.ivRankLevel3?.isVisible = false
                    binding?.llRankInfo3?.isVisible = false

                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (it.pictures?.isNotEmpty() == true){
                        it.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                        }
                    }
                    val imageSize = imageList?.size?:0
                    if(imageSize > 2) {
                        binding?.ivRankImage1?.isVisible = true
                        binding?.ivRankImage2?.isVisible = true
                        binding?.vRankMask2?.isVisible = true
                        binding?.ivRankImage3?.isVisible = true
                        binding?.vRankMask3?.isVisible = true
                        showImage(binding?.ivRankImage1, imageList?.get(0))
                        showImage(binding?.ivRankImage2, imageList?.get(1))
                        showImage(binding?.ivRankImage3, imageList?.get(2))

                    } else if(imageSize == 2){
                        binding?.ivRankImage1?.isVisible = true
                        binding?.vRankMask2?.isVisible = true
                        binding?.ivRankImage2?.isVisible = true
                        binding?.ivRankImage3?.isVisible = false
                        showImage(binding?.ivRankImage1, imageList?.get(0))
                        showImage(binding?.ivRankImage2, imageList?.get(1))
                    } else if(imageSize == 1){
                        binding?.ivRankImage1?.isVisible = true
                        binding?.ivRankImage2?.isVisible = false
                        binding?.ivRankImage3?.isVisible = false
                        showImage(binding?.ivRankImage1, imageList?.get(0))
                    }
                    binding?.ivRankImage1?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }

                    }
                    binding?.ivRankImage2?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                    binding?.ivRankImage3?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                }
            }
            campRankList.size == 2 ->{
                campRankList[0].let {
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (it.pictures?.isNotEmpty() == true){
                        it.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                        }
                    }
                    showImage(binding?.ivRankImage1, imageList?.get(0))
                    binding?.ivRankImage1?.isVisible = true
                    binding?.vRankMask1?.isVisible = true
                    binding?.ivRankLevel1?.isVisible = true
                    binding?.llRankInfo1?.isVisible = true
                    binding?.tvRankName1?.text = it.campName
                    binding?.tvRankDistance1?.text = it.distance?.toFloat()?.let{ distance ->
                        "${DecimalFormat("0.##").format(distance / 1000)}km"
                    }
                    binding?.ivRankImage1?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                }

                campRankList[1].let {
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (it.pictures?.isNotEmpty() == true){
                        it.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                        }
                    }
                    showImage(binding?.ivRankImage2, imageList?.get(0))
                    binding?.ivRankImage2?.isVisible = true
                    binding?.vRankMask2?.isVisible = true
                    binding?.ivRankLevel2?.isVisible = true
                    binding?.llRankInfo2?.isVisible = true
                    binding?.tvRankName2?.text = it.campName
                    binding?.tvRankDistance2?.text = it.distance?.toFloat()?.let{ distance ->
                        "${DecimalFormat("0.##").format(distance / 1000)}km"
                    }
                    binding?.ivRankImage2?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                }

                binding?.ivRankImage3?.isVisible = false
                binding?.vRankMask3?.isVisible = false
                binding?.ivRankLevel3?.isVisible = false
                binding?.llRankInfo3?.isVisible = false

            }
            campRankList.size > 2 ->{
                campRankList[0].let {
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (it.pictures?.isNotEmpty() == true){
                        it.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                        }
                    }
                    showImage(binding?.ivRankImage1, imageList?.get(0))
                    binding?.ivRankImage1?.isVisible = true
                    binding?.vRankMask1?.isVisible = true
                    binding?.ivRankLevel1?.isVisible = true
                    binding?.llRankInfo1?.isVisible = true
                    binding?.tvRankName1?.text = it.campName
                    binding?.tvRankDistance1?.text = it.distance?.toFloat()?.let{ distance ->
                        "${DecimalFormat("0.##").format(distance / 1000)}km"
                    }
                    binding?.ivRankImage1?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                }
                campRankList[1].let {
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (it.pictures?.isNotEmpty() == true){
                        it.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                        }
                    }
                    showImage(binding?.ivRankImage2, imageList?.get(0))
                    binding?.ivRankImage2?.isVisible = true
                    binding?.vRankMask2?.isVisible = true
                    binding?.ivRankLevel2?.isVisible = true
                    binding?.llRankInfo2?.isVisible = true
                    binding?.tvRankName2?.text = it.campName
                    binding?.tvRankDistance2?.text = it.distance?.toFloat()?.let{ distance ->
                        "${DecimalFormat("0.##").format(distance / 1000)}km"
                    }
                    binding?.ivRankImage2?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                }
                campRankList[2].let {
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (it.pictures?.isNotEmpty() == true){
                        it.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                        }
                    }
                    showImage(binding?.ivRankImage3, imageList?.get(0))
                    binding?.ivRankImage3?.isVisible = true
                    binding?.vRankMask3?.isVisible = true
                    binding?.ivRankLevel3?.isVisible = true
                    binding?.llRankInfo3?.isVisible = true
                    binding?.tvRankName3?.text = it.campName
                    binding?.tvRankDistance3?.text = it.distance?.toFloat()?.let{ distance ->
                        "${DecimalFormat("0.##").format(distance / 1000)}km"
                    }
                    binding?.ivRankImage3?.click { view ->
                        activity?.let { act->
                            PrivacyManager.checkPrivacy(act, action = {
                                PlaceDetailActivity.open(requireContext(), it.id, it.campName?:"", "home_top_rank")
                            })
                        }
                    }
                }
            }
            else ->{}
        }
    }

    fun showImage(imageView : SimpleDraweeView?, imageInfo : ImageInfo?){
        if (imageInfo?.source?.isNotEmpty() == true){
            ImageUtil.updateImageFromNetwork(imageView, imageInfo.source)
        }else{
            ImageUtil.updateImageFromNetwork(imageView, imageInfo?.url)
        }
    }



    fun onPlaceSelectUpdate(item : AreaItem){
        if(item.id != -1L){
            binding?.tvFilterArea?.text = item.name
        } else {
            binding?.tvFilterArea?.text = "全国"
        }
        mViewModel.selectedItem.value = item
        mViewModel.onRefresh(showProgress = true)
        mViewModel.requestRankData(mPlaceAreaViewModel.areaData.value?.provinces)
    }

    fun onConditionSelectUpdate(selectedConditionList : MutableMap<Int, MutableList<Int>>?){
        filterConditionCategoryContentAdapter?.updateSelectedCondition(selectedConditionList)
        hotConditionAdapter?.updateSelectedCondition(selectedConditionList)
        conditionCategoryAdapter?.updateSelectedCondition(selectedConditionList)
    }

    fun updateConditionData(data : List<CampConditionTree>?){
        conditionCategoryAdapter?.setData(data)
        conditionCategoryPanelAdapter?.setData(data)
    }

    fun updateHotConditionData(data : List<CampHotConditionItem>?){
        binding?.rvHotCondition?.visibility = if(data?.isNotEmpty() == true) View.VISIBLE else View.GONE
        hotConditionAdapter?.setData(data)
    }

    fun updateModelUi(){
        if(mViewModel.uiModel == UI_MODEL_MAP){//map
            binding?.clListUi?.visibility = View.GONE
            binding?.clMapUi?.visibility = View.VISIBLE
            binding?.clFilterAndContentBg?.visibility = View.GONE
            binding?.mapContainer?.visibility = View.VISIBLE
        }else {
            binding?.clListUi?.visibility = View.VISIBLE
            binding?.clMapUi?.visibility = View.GONE
            binding?.clFilterAndContentBg?.visibility = View.VISIBLE
            binding?.mapContainer?.visibility = View.INVISIBLE
        }
        updateUIForAppBar()
        updateUIForOrderFilter()
    }

    //更新菜单模块
    fun updateUIForAppBar(){
        if(mViewModel.uiModel == UI_MODEL_MAP){
            binding?.btnChangeToList?.visibility = View.VISIBLE
            binding?.btnChangeToMap?.visibility = View.GONE
            binding?.clTopSearchBarBg?.setBackgroundResource(R.drawable.bg_white_0_0_0_0)
            binding?.vSearchBarTopPadding?.layoutParams?.let {
                it.height = BarUtils.getStatusBarHeight()
            }
            binding?.llSearchInfo?.layoutParams?.let {
                it.height = 32.dp
                (it as ConstraintLayout.LayoutParams).bottomMargin = 6.dp
            }
            binding?.clFilterAndContent?.layoutParams?.let {
                (it as CoordinatorLayout.LayoutParams).topMargin = 0.dp
            }
            binding?.clFilterInfo?.setPadding(0, 6.dp, 0, 0)
            binding?.flFilter?.setPadding(0, 6.dp, 0, 0)
            binding?.ivFilterArea?.layoutParams?.let {
                it.width = 19.dp
                it.height = 19.dp
            }
            binding?.tvFilterArea?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20f)

            binding?.llSearchInfo?.background = gradientDrawableBuild {
                solidColor = Color.parseColor("#F6F6F6")
                cornerRadius = 20.dp.toFloat()
            }
            binding?.tvSearch?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
            binding?.ivSearch?.layoutParams?.let {
                it.width = 16.dp
                it.height = 16.dp
            }

            binding?.nsflFilterInfo?.isNestedScrollingEnabled = false

            binding?.collapsingToolbarLayout?.minimumHeight =  50.dp
            binding?.clTopLoading?.layoutParams?.let {
                it.height = 50.dp
            }

        } else {
            binding?.btnChangeToList?.visibility = View.GONE
            val totalScrollRange = (binding?.appBarLayout?.totalScrollRange?:0)
            if( totalScrollRange > 0 && totalScrollRange + appBarOffset == 0){
                //appbar收起了
                binding?.btnChangeToMap?.visibility = View.VISIBLE
                binding?.clTopSearchBarBg?.setBackgroundResource(R.drawable.bg_camp_list_fragment)
                binding?.vSearchBarTopPadding?.layoutParams?.let {
                    it.height = BarUtils.getStatusBarHeight()
                }
                binding?.llSearchInfo?.layoutParams?.let {
                    it.height = 32.dp
                    (it as ConstraintLayout.LayoutParams).bottomMargin = 6.dp
                }
                binding?.clFilterAndContent?.layoutParams?.let {
                    (it as CoordinatorLayout.LayoutParams).topMargin = 6.dp
                }
                binding?.clFilterInfo?.setPadding(0, 0, 0, 0)
                binding?.flFilter?.setPadding(0, 0, 0, 0)
                binding?.ivFilterArea?.layoutParams?.let {
                    it.width = 19.dp
                    it.height = 19.dp
                }
                binding?.tvFilterArea?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20f)
                binding?.llSearchInfo?.background = gradientDrawableBuild {
                    solidColor = Color.parseColor("#FFFFFF")
                    cornerRadius = 20.dp.toFloat()
                }
                binding?.tvSearch?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
                binding?.ivSearch?.layoutParams?.let {
                    it.width = 16.dp
                    it.height = 16.dp
                }

                binding?.nsflFilterInfo?.isNestedScrollingEnabled = false

                binding?.collapsingToolbarLayout?.minimumHeight =  50.dp
                binding?.clTopLoading?.layoutParams?.let {
                    it.height = 50.dp
                }

            } else {
                binding?.btnChangeToMap?.visibility = View.GONE
                binding?.clTopSearchBarBg?.setBackgroundResource(R.drawable.bg_camp_list_fragment)
                binding?.vSearchBarTopPadding?.layoutParams?.let {
                    it.height = BarUtils.getStatusBarHeight()
                }
                binding?.llSearchInfo?.layoutParams?.let {
                    it.height = 39.dp
                    (it as ConstraintLayout.LayoutParams).bottomMargin = 3.dp
                }
                binding?.clFilterAndContent?.layoutParams?.let {
                    (it as CoordinatorLayout.LayoutParams).topMargin = 0.dp
                }
                binding?.clFilterInfo?.setPadding(0, 0, 0, 0)
                binding?.flFilter?.setPadding(0, 0, 0, 0)

                binding?.ivFilterArea?.layoutParams?.let {
                    it.width = 24.dp
                    it.height = 24.dp
                }
                binding?.tvFilterArea?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24f)

                binding?.llSearchInfo?.background = gradientDrawableBuild {
                    solidColor = Color.parseColor("#FFFFFF")
                    cornerRadius = 20.dp.toFloat()
                }
                binding?.tvSearch?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13f)
                binding?.ivSearch?.layoutParams?.let {
                    it.width = 20.dp
                    it.height = 20.dp
                }

                binding?.nsflFilterInfo?.isNestedScrollingEnabled = true

                binding?.collapsingToolbarLayout?.minimumHeight =  50.dp
                binding?.clTopLoading?.layoutParams?.let {
                    it.height = 50.dp
                }
            }
        }
    }

    fun updateUIForOrderFilter(){
        binding?.ivFilterDistance?.isVisible = false
        binding?.ivFilterPopularity?.isVisible = false
        binding?.ivFilterGood?.isVisible = false
        binding?.tvFilterDistance?.setTextColor(Color.parseColor("#999999"))
        binding?.tvFilterPopularity?.setTextColor(Color.parseColor("#999999"))
        binding?.tvFilterGood?.setTextColor(Color.parseColor("#999999"))

        when(mViewModel.currentScreen){
            PlaceSortType.Distance -> {
                binding?.ivFilterDistance?.isVisible = true
                binding?.tvFilterDistance?.setTextColor(Color.parseColor("#20211F"))
            }
            PlaceSortType.Popularity -> {
                binding?.ivFilterPopularity?.isVisible = true
                binding?.tvFilterPopularity?.setTextColor(Color.parseColor("#20211F"))
            }
            PlaceSortType.GoodEvaluation -> {
                binding?.ivFilterGood?.isVisible = true
                binding?.tvFilterGood?.setTextColor(Color.parseColor("#20211F"))
            }
            else -> {}
        }
    }


    var placeListChange = false
    fun updateMapModelUI(isClick:Boolean = false){
        if(!isClick){
            placeListChange = true
        }
        if(mViewModel.uiModel == UI_MODEL_MAP){
            val list: List<CampListItem> = mViewModel.placeList.value?: mutableListOf()
            updateBanner(list, placeListChange)

            if(isShowNumberMarker != true && mViewModel.selectedItem.value?.id == -1L){
                moveCameraForAllCity()
            }
            updateMarker(aMap?.cameraPosition, placeListChange)

            placeListChange = false
        }
    }

    override fun onPlaceClick(item: CampListItem) {
        activity?.let {
            PrivacyManager.checkPrivacy(it, action = {
                item.id?.let {
                    val mode = if(mViewModel.uiModel == UI_MODEL_MAP) "map" else "list"
                    val sorting = when (mViewModel.currentScreen){
                        PlaceSortType.Distance -> "distance"
                        PlaceSortType.Popularity -> "popularity"
                        PlaceSortType.GoodEvaluation -> "good_evaluation"
                        else -> {""}
                    }
                    PlaceDetailActivity.open(requireContext(), it, item.campName?:"", "camp_list", mode = mode, sorting = sorting)
                }
            })
        }
    }


    //列表模式-----------------------------
    private fun initListModelUI(){
        adapter = CampListAdapter()
        adapter?.setHasStableIds(true)
        binding?.recycleView?.layoutManager = LinearLayoutManager(requireContext())
        binding?.recycleView?.adapter = adapter
        adapter?.onPlaceClickListener = this

        binding?.refreshLayout?.setEnableRefresh(false)

        binding?.refreshLayout?.setOnLoadMoreListener {
            mViewModel.onLoadMore()
        }


        mViewModel.errorShow.observe(viewLifecycleOwner, Observer<Boolean> {
            if(it == true){
                binding?.statusView?.setStatus(StatusView.NET_ERROR, updateActionBtn = { btn ->
                    btn.click {
                        mViewModel.onRefresh(showProgress = true)
                    }
                })
            } else {
                binding?.statusView?.setStatus(StatusView.IDLE)
            }
        })

        mViewModel.placeListHasMore.observe(viewLifecycleOwner, Observer<Boolean> {
            if(it == true){
                binding?.refreshLayout?.resetNoMoreData()
            } else {
                binding?.refreshLayout?.setNoMoreData(true)
            }
        })
        mViewModel.scrollToTop.observe(viewLifecycleOwner, Observer {
            if(it == true){
                binding?.recycleView?.scrollToPosition(0)
            }
        })
        mViewModel.placeList.observe(viewLifecycleOwner, Observer<List<CampListItem>> {
            adapter?.setData(it)
            if(it.isEmpty()){
                binding?.statusView?.setStatus(
                    StatusView.NO_DATA,
                    isCenter = false,
                    marginTop = 32.dp,
                    msg = "暂无相关营地哦～",
                    imgSrc = R.drawable.pic_no_content_camp,
                    imgWidth = 241.dp,
                    imgHeight = 116.dp,
                )
            } else {
                binding?.statusView?.setStatus(StatusView.IDLE)
            }
        })

        UserManager.instance.campCollect.observe(viewLifecycleOwner, Observer {
            adapter?.notifyDataSetChanged()
        })
    }


    //地图相关-----------------------------

    val showCampMarkerZoomLevel = 8f  //局部
    val showNumberMarkerZoomLevelLimit = 6f  //全国界限
    val showNumberMarkerZoomLevel = 4f  //全国
    val maxZoomLevel = 18.8f  //最大放大等级

    var isShowNumberMarker:Boolean? = null
    var hasUpdateMarker:Boolean = false

    val numberMarkerMap = mutableMapOf<String, Marker?>()
    val campMarkerMap = mutableMapOf<String, Marker?>()

    var campBannerAdapter : CampBannerAdapter? = null

    //地图模式初始化
    fun initMapModelUI(){
        //地图模式 相关
        mViewModel.focusCampItem.observe(viewLifecycleOwner, Observer { item ->
            item?.let {
                moveCamera(it)
                val layoutManager: LinearLayoutManager?  = binding?.banner?.layoutManager as LinearLayoutManager?
                if(layoutManager != null){
                    val first = layoutManager.findFirstCompletelyVisibleItemPosition()
                    val temp = campBannerAdapter?.getDataItem(first)
                    if(temp != null && temp.id != it.id){
                        val position = campBannerAdapter?.getPosition(it)
                        if(position != null && position >= 0){
                            binding?.banner?.scrollToPosition(position)
                        }
                    }
                }
            }
            if(item == null){
                mViewModel.currentLatLng = null
                if(mViewModel.isReset){
                    hasUpdateMarker = true
                    moveCamera(mViewModel.myLatLng, showCampMarkerZoomLevel)
                }
            }
        })
        mViewModel.nationNumList.observe(viewLifecycleOwner, Observer {
            if(isShowNumberMarker != true && mViewModel.selectedItem.value?.id == -1L){
                moveCameraForAllCity()
            }
            updateMarker(aMap?.cameraPosition, true)
        })

        mapView = binding?.map
        mapView?.onCreate(null)
        aMap = binding?.map?.map
        aMap?.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        //LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER 连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        // 设置定位的类型为根据地图面向方向旋转
        aMap?.myLocationStyle = MyLocationStyle().interval(10000).myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
        //marker 点击事件
        aMap?.setOnMarkerClickListener(this)
        //marker 对应infowindow 点击事件
        aMap?.setOnInfoWindowClickListener(this)

        //aMap.uiSettings.isMyLocationButtonEnabled = true //设置默认定位按钮是否显示，非必需设置。
        aMap?.uiSettings?.isScaleControlsEnabled = true //比例尺
        aMap?.uiSettings?.isZoomControlsEnabled = false
        aMap?.maxZoomLevel = maxZoomLevel
        try {
            val mapStyle = CustomMapStyleOptions()
            val styleData = resources.assets.open("style.data")
            val styleExtraData = resources.assets.open("style_extra.data")
            mapStyle.setStyleData(styleData.readBytes())
            mapStyle.setStyleExtraData(styleExtraData.readBytes())
            aMap?.setCustomMapStyle(mapStyle)
        }catch (e:Exception){
        }

        aMap?.setOnCameraChangeListener(object : AMap.OnCameraChangeListener {
            override fun onCameraChange(cameraPosition: CameraPosition?) {
            }

            override fun onCameraChangeFinish(cameraPosition: CameraPosition?) {
                updateMarker(cameraPosition)
            }
        })

        aMap?.isTrafficEnabled = false
        binding?.btnChangeMapType?.click {
            if(aMap?.mapType == AMap.MAP_TYPE_SATELLITE){
                aMap?.mapType = AMap.MAP_TYPE_NORMAL
                binding?.btnChangeMapType?.setImageResource(R.drawable.icon_satellite_map)
                try {
                    val mapStyle = CustomMapStyleOptions()
                    val styleData = resources.assets.open("style.data")
                    val styleExtraData = resources.assets.open("style_extra.data")
                    mapStyle.setEnable(true)
                    mapStyle.setStyleData(styleData.readBytes())
                    mapStyle.setStyleExtraData(styleExtraData.readBytes())
                    aMap?.setCustomMapStyle(mapStyle)
                }catch (e:Exception){
                }


            } else {
                aMap?.mapType = AMap.MAP_TYPE_SATELLITE
                binding?.btnChangeMapType?.setImageResource(R.drawable.icon_plane_map)
            }
        }

        binding?.btnCurrentLocation?.click {
            mViewModel.resetMyLocation()
        }

        mViewModel.placeList.observe(viewLifecycleOwner, Observer<List<CampListItem>> {
            updateMapModelUI()
        })

    }

    fun updateBanner(list: List<CampListItem>, isPlaceListChange:Boolean = false){
        if(campBannerAdapter == null){
            campBannerAdapter = CampBannerAdapter()
            campBannerAdapter?.onPlaceClickListener = this
            binding?.banner?.setAdapter(campBannerAdapter)
            binding?.banner?.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
            PagerSnapHelper().attachToRecyclerView(binding?.banner)
            binding?.banner?.addOnScrollListener(object : RecyclerView.OnScrollListener() {

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if(newState == RecyclerView.SCROLL_STATE_IDLE){
                        val layoutManager: LinearLayoutManager?  = binding?.banner?.layoutManager as LinearLayoutManager?
                        if(layoutManager != null){
                            val first = layoutManager.findFirstCompletelyVisibleItemPosition()
                            val temp = campBannerAdapter?.getDataItem(first)
                            if(temp != null && temp.id != empty_id && mViewModel.focusCampItem.value != null
                                && mViewModel.focusCampItem.value!!.id != temp.id ){
                                mViewModel.focusCampItem.value = temp
                            }
                        }
                    }
                }
            })
        }
        campBannerAdapter?.setData(list)
        if(list.isNotEmpty()){
            if(isPlaceListChange){
                if(mViewModel.selectedItem.value?.id != -1L){ //不是选全国
                    for(item in list){
                        if(item.id != empty_id){
                            mViewModel.focusCampItem.value = item
                            break
                        }
                    }
                    binding?.banner?.scrollToPosition(0)
                } else {
                    mViewModel.focusCampItem.value = null
                }
            }
        } else {
            mViewModel.focusCampItem.value = null
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mapView?.onSaveInstanceState(outState)
    }

    override fun onPause() {
        super.onPause()
        mapView?.onPause()
        aMap?.isMyLocationEnabled = false
    }

    override fun onDestroy() {
        super.onDestroy()
        aMap?.removeOnInfoWindowClickListener(this)
        aMap?.removeOnMarkerClickListener(this)
        mapView?.onDestroy()
    }


    fun updateMarker(cameraPosition: CameraPosition?, isPlaceListChange:Boolean = false){
        if(cameraPosition?.zoom != null){
            if(mViewModel.selectedItem.value?.id == -1L){
                //全国
                if(isPlaceListChange || hasUpdateMarker || isShowNumberMarker != true){
                    if(isShowNumberMarker == null || isShowNumberMarker != true){
                    }
                    mapShowNumberMarker()
                }
            } else {
                if(cameraPosition.zoom > showNumberMarkerZoomLevelLimit && (isPlaceListChange || hasUpdateMarker || isShowNumberMarker == true)){
                    if(isShowNumberMarker == null || isShowNumberMarker == true){
                    }
                    //局部
                    mapShowCampMarker()
                }else if(cameraPosition.zoom < showNumberMarkerZoomLevelLimit && (isPlaceListChange || hasUpdateMarker || isShowNumberMarker != true)){
                    if(isShowNumberMarker == null || isShowNumberMarker != true){
                    }
                    //全国
                    mapShowNumberMarker()
                }
            }
            hasUpdateMarker = false
        }
    }

    fun mapShowNumberMarker(){
        isShowNumberMarker = true
        clearMarker()
        if(mViewModel.nationNumList.value != null){
            for(item in mViewModel.nationNumList.value!!){
                if(item.latitude?.isNotEmpty() == true && item.longitude?.isNotEmpty() == true){
                    val view = LayoutInflater.from(requireContext()).inflate(R.layout.layout_number_marker, null, false)
                    view.findViewById<TextView>(R.id.tv_number).text = "${item.camp_num?:0}个"
                    val key = "number_${item.ad_code}"
                    val marker = aMap?.addMarker(
                        MarkerOptions().position(LatLng(item.latitude!!.toDouble(), item.longitude!!.toDouble())).title(key)
                            .icon(BitmapDescriptorFactory.fromView(view))
                    )
                    numberMarkerMap.put(key, marker)
                }
            }
        }

        binding?.banner?.visibility = View.GONE
        binding?.cardviewEmpty?.visibility = View.GONE
    }

    fun mapShowCampMarker(){
        isShowNumberMarker = false
        clearMarker()
        if(mViewModel.placeList.value != null){
            for(item in  mViewModel.placeList.value!!){
                if(item.latitude?.isNotEmpty() == true && item.longitude?.isNotEmpty() == true){
                    var marker:Marker? = null
                    val key = "camp_${item.id}"
                    if(mViewModel.focusCampItem.value != null
                        && mViewModel.focusCampItem.value!!.id == item.id){
                        marker = aMap?.addMarker(
                            MarkerOptions().position(LatLng(item.latitude!!.toDouble(), item.longitude!!.toDouble()) ).title(key)
                                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.icon_camp_marker_sel)))
                        )
                        marker?.zIndex = 10f
                        lastSelectMarker = marker
                    }else {
                        marker = aMap?.addMarker(
                            MarkerOptions().position(LatLng(item.latitude!!.toDouble(), item.longitude!!.toDouble()) ).title(key)
                                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_camp_marker_nor)))
                        )
                        marker?.zIndex = 1f
                    }

                    campMarkerMap.put(key, marker)
                }
            }
        }

        val list: List<CampListItem> = mViewModel.placeList.value?: mutableListOf()
        if(list.isNotEmpty()){
            binding?.banner?.visibility = View.VISIBLE
            binding?.cardviewEmpty?.visibility = View.GONE
        }else {
            binding?.banner?.visibility = View.GONE
            binding?.cardviewEmpty?.visibility = View.VISIBLE
        }
    }

    fun clearMarker(){
        for (marker in numberMarkerMap.values){
            marker?.remove()
        }
        numberMarkerMap.clear()
        for (marker in campMarkerMap.values){
            marker?.remove()
        }
        campMarkerMap.clear()
    }

    override fun onInfoWindowClick(p0: Marker?) {
    }

    override fun onMarkerClick(marker: Marker?): Boolean {
        if(marker?.title?.contains("number_") == true){
            val adCode = marker.title.split("_")[1]
            if(mViewModel.nationNumList.value != null){
                for(item in  mViewModel.nationNumList.value!!){
                    if(item.ad_code == adCode){
                        if(item.latitude?.isNotEmpty() == true && item.longitude?.isNotEmpty() == true){
                            moveCamera(LatLng(item.latitude!!.toDouble(), item.longitude!!.toDouble()), showNumberMarkerZoomLevel)
                            val targetArea = mPlaceAreaViewModel.findTargetArea(item.ad_code?:"")
                            if(targetArea != null){
                                onPlaceSelect(targetArea, "map")
                            }else {
                                Toast.makeText(requireContext(), "找不到地区", Toast.LENGTH_SHORT).show()
                            }
                        }
                        break
                    }
                }
            }

        } else if(marker?.title?.contains("camp_") == true){
            updateSelectedMarker(marker)
            val id = marker.title.split("_")[1].toInt()
            if(mViewModel.placeList.value != null){
                for(item in  mViewModel.placeList.value!!){
                    if(item.id == id){
                        mViewModel.focusCampItem.postValue(item)
                        break
                    }
                }
            }
        }
        return true
    }

    fun moveCameraForAllCity(){
        hasUpdateMarker = true
        moveCamera(mViewModel.myLatLng, showNumberMarkerZoomLevel)
    }

    fun moveCamera(item: CampListItem?){
        item?.let {
            if(it.latitude?.isNotEmpty() == true && it.longitude?.isNotEmpty() == true){
                mViewModel.currentLatLng = LatLng(it.latitude!!.toDouble(), it.longitude!!.toDouble())
                var level:Float = if(isShowNumberMarker == true) showCampMarkerZoomLevel else aMap?.cameraPosition?.zoom?:showCampMarkerZoomLevel
                moveCamera(mViewModel.currentLatLng, level)
                for (marker in campMarkerMap.values){
                    if(marker?.title?.contains("camp_") == true){
                        val id = marker.title.split("_")[1].toInt()
                        if(item.id == id){
                            updateSelectedMarker(marker)
                            break
                        }
                    }
                }
            }
        }
    }

    fun moveCamera(latlng: LatLng?, level:Float = showCampMarkerZoomLevel){
        latlng?.let {
            mViewModel.isReset = false
            val cameraUpdate = CameraUpdateFactory.newCameraPosition(CameraPosition(it, level, 0f ,0f))
            aMap?.animateCamera(cameraUpdate)
        }
    }

    var lastSelectMarker: Marker? = null
    fun updateSelectedMarker(marker: Marker?){
        if(lastSelectMarker != null && lastSelectMarker?.isRemoved != true && lastSelectMarker != marker){
            lastSelectMarker?.zIndex = 1f
            lastSelectMarker?.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.icon_camp_marker_nor)))
        }
        marker?.zIndex = 10f
        marker?.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.icon_camp_marker_sel)))
        lastSelectMarker = marker
    }
}